package com.hbt.api.interceptor;

import com.hbt.api.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("enter loginInterceptor");

//        if (redisTemplate == null) System.out.println("redistemplate is null*****");
        String token = (String) request.getParameter("token");
        System.out.println("进入拦截器token:"+token);
        if(token == null || token.equals("")){
            request.getRequestDispatcher("/nologin").forward(request,response);
        }else {
            //判断token对应redis中的值是否已经过期，过期返回请求转发， 不过期则return true且刷新时间
            if(isExpire(token)){
                request.getRequestDispatcher("/nologin").forward(request,response);
                return false;
            }
            //刷新token对应redis中的值的过期时间
            System.out.println("token time no expire");
            return true;
        }
        return false;
    }
    //判断token对应redis中的键值是否已经过期
    public boolean isExpire(String token){
        Jedis jedis = new Jedis("hbt123.xyz");
        String username = jedis.get(token);
        if (username == null || username.equals("")){
            //token过期了
            System.out.println("token time has expire");
            return true;
        }
        return false;
    }

}
